package com.leonzx.base.utils;

import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 邮件发送工具类
 *
 * @Author chen
 * @Date 2018/7/9 14:36
 */
public class JavaMailUtil {

    /**
     * 邮件发送
     *
     * @param login          登录名称
     * @param password       密码
     * @param senderEmail    发件人邮箱
     * @param addresseeEmail 收件人邮箱集合
     * @param title          主题
     * @param content        内容
     * @param fileArr        附件集合
     * @param servicePath    邮件服务器地址
     * @throws Exception
     */
    public static boolean sendMail(String login, String password, String senderEmail, String[] addresseeEmail, String[] copyEmail, String title,
                                   String content, List<String> fileArr, List<Map<String, String>> urlMaps, String servicePath) {
        boolean flag = false;
        Properties prop = new Properties();
        prop.setProperty("mail.host", servicePath);
        prop.setProperty("mail.transport.protocol", "smtp");
        prop.setProperty("mail.smtp.auth", "true");
        //使用JavaMail发送邮件的5个步骤
        //1、创建session
        Session session = Session.getInstance(prop);
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);
        //2、通过session得到transport对象

        //3、连上邮件服务器
        try {
            Transport ts = session.getTransport();
            ts.connect(servicePath, login, password);
            //4、创建邮件
            Message message = createMixedMail(session, senderEmail, addresseeEmail, copyEmail, title, content, fileArr, urlMaps);
            //5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static MimeMessage createMixedMail(Session session, String senderEmail, String[] addresseeEmail, String[] copyEmail, String title,
                                              String content, List<String> fileArr, List<Map<String, String>> urlMaps) throws Exception {
        //1.创建一封邮件的实例对象
        MimeMessage msg = new MimeMessage(session);
        //2.设置发件人地址
        msg.setFrom(new InternetAddress(senderEmail));
        /**
         * 3.设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行
         * MimeMessage.RecipientType.TO:发送
         * MimeMessage.RecipientType.CC：抄送
         * MimeMessage.RecipientType.BCC：密送
         */
        //添加抄送人员

        if(copyEmail != null && copyEmail.length > 0){
            InternetAddress[] sendCo = new InternetAddress[copyEmail.length];
            for (int i = 0; i < copyEmail.length; i++) {
                sendCo[i] = new InternetAddress(copyEmail[i]);
            }
            msg.setRecipients(MimeMessage.RecipientType.CC, sendCo);
        }

        //添加收件人
        if(addresseeEmail != null && addresseeEmail.length > 0){
            InternetAddress[] sendTo = new InternetAddress[addresseeEmail.length];
            for (int i = 0; i < addresseeEmail.length; i++) {
                sendTo[i] = new InternetAddress(addresseeEmail[i]);
            }
            msg.setRecipients(MimeMessage.RecipientType.TO,sendTo);
        }
        //4.设置邮件主题
        msg.setSubject(title, "UTF-8");
        getImgAndFile(msg, content, fileArr, urlMaps);
        //设置邮件的发送时间,默认立即发送
        msg.setSentDate(new Date());

        return msg;
    }

    /**
     * 创建附件及图片
     *
     * @param msg     邮件实体
     * @param fileArr 附件路径数组
     * @return
     * @throws Exception
     */
    public static MimeMessage getImgAndFile(MimeMessage msg, String content, List<String> fileArr, List<Map<String, String>> urlMaps) throws Exception {
        // 5. 创建文本"节点"
        MimeBodyPart text = new MimeBodyPart();
        if(StringUtils.isBlank(content)){
            text.setContent("" , "text/html;charset=UTF-8");
        }else{
            text.setContent(content , "text/html;charset=UTF-8");
        }

        // 6. 创建图片"节点" 和混合节点
        MimeMultipart mm = new MimeMultipart();
        if(urlMaps != null && urlMaps.size() > 0){
            MimeMultipart mm_text_image = new MimeMultipart();
            mm_text_image.addBodyPart(text);
            for (int i = 0; i < urlMaps.size(); i++) {
                Map<String, String> map = urlMaps.get(i);
                for (String key : map.keySet()) {
                    // 读取本地文件
                    MimeBodyPart image = new MimeBodyPart();
                    String path = map.get(key).replaceAll("\\\\", "/");
                    DataHandler dh = new DataHandler(new FileDataSource(path));
                    // 将图片数据添加到"节点"
                    image.setDataHandler(dh);
                    // 为"节点"设置一个唯一编号（在文本"节点"将引用该ID）
                    image.setContentID(key);
                    mm.addBodyPart(image);
                }
            }
        }
        if(fileArr != null && fileArr.size() > 0){
            for (int i = 0; i < fileArr.size(); i++) {
                MimeBodyPart attachment = new MimeBodyPart();
                // 读取本地文件
                DataHandler dh2 = new DataHandler(new FileDataSource(fileArr.get(i)));
                // 将附件数据添加到"节点"
                attachment.setDataHandler(dh2);
                attachment.setFileName(dh2.getName());
                mm.addBodyPart(attachment);     // 如果有多个附件，可以创建多个多次添加
            }
        }
        mm.addBodyPart(text);
        mm.setSubType("mixed");         // 混合关系
        // 9. 设置整个邮件的关系（将最终的混合"节点"作为邮件的内容添加到邮件对象）
        msg.setContent(mm);
        return msg;
    }

    public static void main(String[] args) throws Exception {
//        sendMail("1041834313@qq.com", "ebkyeyrokpjjbbbe", "1041834313@qq.com", "1041834313@qq.com".split(","), "测试", "啦啦啦啦", null, null, "smtp.qq.com");
    }
}
